package com.czp.ssm.shiro;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.czp.ssm.bean.User;
import com.czp.ssm.bean.UserRole;
import com.czp.ssm.dao.UserMapper;
import com.czp.ssm.dao.UserRoleMapper;

public class ShiroRealm extends AuthorizingRealm {

	@Autowired
	private UserMapper userMapper;
	@Autowired
	private UserRoleMapper userRoleMapper;
	
	
	//认证方法
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		System.out.println("-----------开始认证");
		UsernamePasswordToken userToken = (UsernamePasswordToken) token;
		SimpleAuthenticationInfo info = null; 
		String username = userToken.getUsername();
		User user = userMapper.selectUserByUserPhone(username);
		System.out.println("user-------"+user);
		if (user != null) {
//			User principal = user;
			Object credentials = user.getUserPassword();
			String realmName = getName();
			ByteSource credentialsSalt = ByteSource.Util.bytes(user.getUserPhone());
			info = new SimpleAuthenticationInfo(user, credentials, credentialsSalt, realmName);
		}else {
			throw new UnknownAccountException("用户不存在，认证失败");
		}
		return info;
	}

	//授权方法
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		User user = (User)principals.getPrimaryPrincipal();
		List<UserRole> userRoles = userRoleMapper.selectRoleListByUserId(user.getUserId());
		Set<String> roles = new HashSet<String>();
		for (int i = 0; i < userRoles.size(); i++) {
			UserRole userRole = userRoles.get(i);
			if ("0".equals(userRole.getRoleId())) {
				roles.add("admin");
			}
			if ("1".equals(userRole.getRoleId())) {
				roles.add("user");
			}
		}
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
		return info;
	}
}
